<template>
  <div id="system-account">
    <div class="role-info">
      <div style="width: 100%;margin: 0 auto;">
        <h3>角色信息</h3>
        <el-button
          icon="el-icon-circle-plus-outline"
          type="text"
          size="mini"
          style="float: right; margin-top: -30px;margin-right: 10px;"
          @click="addOp('role')"
        >新增
        </el-button>
      </div>
      <el-table
        ref="roleTblRef"
        :data="roleTblData"
        border
        style="width: 100%"
        max-height="230"
        cell-class-name="cellClass"
        header-cell-class-name="headerClass"
      >
        <el-table-column
          v-for="item in roleHeader"
          :key="item.prop"
          :prop="item.prop"
          :label="item.label"
          :width="item.width"
        >
          <template slot-scope="scope">
            <div v-if="item.isOp">
              <el-button type="text" size="small" @click="editOp('role', scope.row)">编辑</el-button>
              <el-button type="text" size="small" @click="deleteOp('role', scope.row)">删除</el-button>
            </div>
            <span v-else>{{ scope.row[item.prop] }}</span>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :current-page="roleCurrentPage"
        :page-sizes="[3, 5, 10, 20]"
        :page-size="rolePageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="roleTotalSize"
        style="float:right;"
        @size-change="handleRoleSizeChange"
        @current-change="handleRoleCurrentChange"
      />
    </div>
    <el-divider />
    <div class="user-info">
      <div style="width: 100%;margin: 0 auto;">
        <h3>系统账户</h3>
        <el-button
          icon="el-icon-circle-plus-outline"
          type="text"
          size="mini"
          style="float: right; margin-top: -30px;margin-right: 10px;"
          @click="addOp('user')"
        >新增
        </el-button>
      </div>
      <el-table
        ref="userTblRef"
        :data="userTblData"
        border
        style="width: 100%;"
        max-height="350"
        cell-class-name="cellClass"
        header-cell-class-name="headerClass"
      >
        <el-table-column
          v-for="item in userHeader"
          :key="item.prop"
          :prop="item.prop"
          :label="item.label"
          :width="item.width"
        >
          <template slot-scope="scope">
            <div v-if="item.isOp">
              <el-button type="text" size="small" @click="editOp('user', scope.row)">编辑</el-button>
              <el-button type="text" size="small" @click="deleteOp('user', scope.row)">删除</el-button>
            </div>
            <div v-else-if="item.isAvatar">
              <el-image
                style="width: 50px; height: 50px"
                :src="getImgUrl(scope.row[item.prop])"
                :preview-src-list="[getImgUrl(scope.row[item.prop])]"
              >
                <div slot="error" class="image-slot">
                  <i class="el-icon-picture-outline"/>
                </div>
              </el-image>
            </div>
            <span v-else-if="item.isPass">{{ '********' }}</span>
            <span v-else>{{ scope.row[item.prop] }}</span>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :current-page="userCurrentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="userPageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="userTotalSize"
        style="float:right;"
        @size-change="handleUserSizeChange"
        @current-change="handleUserCurrentChange"
      />
    </div>

    <!-- 角色编辑(新增和编辑) -->
    <el-dialog
      v-draggable
      :title="dgTitle"
      :visible.sync="dgVisible"
      width="30%"
      :close-on-click-modal="false"
    >
      <RoleEdit
        v-if="opType === 'role'"
        :edit-type="roleEditType"
        :role-info="roleInfo"
        @submit-edit="handleSubmit"
        @cancel-edit="handleCancel"
      />
      <UserEdit
        v-else
        :edit-type="userEditType"
        :role-list="editUserRoleList"
        :user-info="userInfo"
        @submit-edit="handleSubmit"
        @cancel-edit="handleCancel"
      />
    </el-dialog>
  </div>
</template>

<script>
import { updateRoleInfo, getRoleInfo } from '@/api/role'
import { updateUser, getUserList } from '@/api/user'
import RoleEdit from '@/views/systemSetting/usermanagement/systemaccount/RoleEdit.vue'
import UserEdit from '@/views/systemSetting/usermanagement/systemaccount/UserEdit.vue'

export default {
  name: 'SystemAccount',
  components: { UserEdit, RoleEdit },
  data() {
    return {
      // 用户信息
      userHeader: [{
        prop: 'username',
        label: '用户名'
      }, {
        prop: 'password',
        label: '密码',
        isPass: true
      }, {
        prop: 'nickName',
        label: '用户昵称'
      }, {
        prop: 'roleDesc',
        label: '角色描述'
      }, {
        prop: 'avatar',
        label: '头像',
        isAvatar: true
      }, {
        prop: 'email',
        label: '邮箱地址'
      }, {
        prop: 'isAlive',
        label: '是否可用'
      }, {
        prop: 'createTime',
        label: '创建时间'
      }, {
        prop: 'updateTime',
        label: '更新时间'
      }, {
        prop: 'operation',
        label: '操作',
        isOp: true,
        width: '150px'
      }],
      userTblData: [],
      userCurrentPage: 1,
      userTotalSize: 0,
      userPageSize: 10,
      userEditType: 'edit',
      userInfo: {},
      editUserRoleList: [],

      // 角色信息
      roleHeader: [{
        prop: 'roleName',
        label: '角色名称'
      }, {
        prop: 'roleDesc',
        label: '角色描述'
      }, {
        prop: 'createTime',
        label: '创建时间'
      }, {
        prop: 'isAlive',
        label: '是否启用'
      }, {
        prop: 'operation',
        label: '操作',
        isOp: true
      }],
      roleTblData: [],
      roleCurrentPage: 1,
      roleTotalSize: 0,
      rolePageSize: 3,

      // 当前正在操作的对象
      opType: 'role',
      dgTitle: '添加角色',
      dgVisible: false,
      roleEditType: 'edit',
      roleInfo: {}
    }
  },
  mounted() {
    this.initRoleTblData(this.roleCurrentPage, this.rolePageSize)
    this.initUserTblData(this.userCurrentPage, this.userPageSize)
  },
  methods: {
    // 初始化角色信息
    initRoleTblData(currentPage, pageSize) {
      this.roleTblData = []
      getRoleInfo({ currentPage: currentPage, pageSize: pageSize }).then(res => {
        const roleList = res.data
        if (roleList) {
          roleList.forEach(roleInfo => {
            const cpInfo = { ...roleInfo }
            cpInfo['isAlive'] = roleInfo.isActive === 0 ? '不启用' : '启用'
            this.roleTblData.push(cpInfo)
          })
          this.roleTotalSize = res.totalSize
        }
      }).catch(err => {
        console.error(err)
        this.$message.error('获取角色信息失败')
      })
    },

    initUserTblData(currentPage, pageSize) {
      this.userTblData = []
      getUserList({ currentPage: currentPage, pageSize: pageSize }).then(res => {
        const userList = res.data
        if (userList) {
          userList.forEach(userInfo => {
            const cpInfo = { ...userInfo }
            cpInfo['isAlive'] = userInfo.isActive === 0 ? '不启用' : '启用'
            cpInfo['roleDesc'] = userInfo.role.roleDesc
            this.userTblData.push(cpInfo)
          })
          this.userTotalSize = res.totalSize
        }
      }).catch(err => {
        console.error(err)
        this.$message.error('获取用户列表失败')
      })
    },

    // 返回头像全路径
    getImgUrl(originUrl) {
      return process.env.NODE_ENV === 'development' ? process.env.VUE_APP_BASE_API + originUrl : originUrl
    },

    // 角色页码数切换
    handleRoleSizeChange(val) {
      this.rolePageSize = val
      this.initRoleTblData(this.roleCurrentPage, this.rolePageSize)
    },

    // 角色翻页
    handleRoleCurrentChange(val) {
      this.roleCurrentPage = val
      this.initRoleTblData(this.roleCurrentPage, this.rolePageSize)
    },

    // 用户页面码数切换
    handleUserSizeChange(val) {
      this.userPageSize = val
      this.initUserTblData(this.userCurrentPage, this.userPageSize)
    },

    // 用户翻页
    handleUserCurrentChange(val) {
      this.userCurrentPage = val
      this.initUserTblData(this.roleCurrentPage, this.rolePageSize)
    },

    // 新增操作
    addOp(type) {
      if (type === 'role') {
        this.opType = 'role'
        this.dgTitle = '添加角色'
        this.roleEditType = 'add'
        this.roleInfo = {}
      } else {
        // 获取全量角色信息
        getRoleInfo({ currentPage: 1, pageSize: 9999 }).then(res => {
          this.editUserRoleList = res.data
          this.opType = 'user'
          this.dgTitle = '添加用户'
          this.userEditType = 'add'
          this.userInfo = {}
        }).catch(err => {
          console.error(err)
        })
      }
      this.dgVisible = true
    },

    // 编辑操作
    editOp(type, tblRow) {
      if (type === 'role') {
        this.opType = 'role'
        this.dgTitle = '编辑角色'
        this.roleEditType = 'edit'
        this.roleInfo = { ...tblRow }
        this.roleInfo['isActive'] = this.roleInfo.isActive + ''
      } else {
        // 获取全量角色信息
        getRoleInfo({ currentPage: 1, pageSize: 9999 }).then(res => {
          this.editUserRoleList = res.data
          this.opType = 'user'
          this.dgTitle = '编辑用户'
          this.userEditType = 'edit'
          this.userInfo = { ...tblRow }
          this.userInfo['isActive'] = this.userInfo.isActive + ''
        }).catch(err => {
          console.error(err)
        })
      }
      this.dgVisible = true
    },

    // 删除操作
    deleteOp(type, tblRow) {
      const reqData = { ...tblRow }
      reqData['isDelete'] = true
      this.$confirm('确认删除？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.handleSubmit(reqData, type)
      })
    },

    handleSubmit(editForm, type) {
      if (!editForm['isDelete']) {
        editForm['isDelete'] = false
      }
      if (type === 'role') {
        updateRoleInfo(editForm).then(res => {
          this.$message.success('操作成功')
          this.initRoleTblData(this.roleCurrentPage, this.rolePageSize)
        }).catch(err => {
          console.error(err)
          this.$message.error('操作失败')
        })
      } else {
        updateUser(editForm).then(res => {
          this.$message.success('操作成功')
          this.initUserTblData(this.userCurrentPage, this.userPageSize)
        }).catch(err => {
          console.error(err)
          this.$message.error('操作失败')
        })
      }
      this.dgVisible = false
    },
    handleCancel() {
      this.dgVisible = false
    }
  }
}
</script>

<style scoped>
#system-account {
  margin: 30px;
}

#system-account /deep/ .headerClass {
  text-align: center;
}

#system-account /deep/ .cellClass {
  text-align: center;
  font-size: 14px;
}

.role-info {
  width: 100%;
  height: 300px;
}

.user-info {
  width: 100%;
  height: 420px;
}
</style>
